#!/bin/bash

# 数据库恢复脚本
# 用法: ./restore-db.sh <backup_file>

# 加载环境变量
set -a
source ../.env
set +a

# 设置变量
BACKUP_DIR="../backups"
DB_NAME=${DATABASE_NAME:-"aicet"}
DB_USER=${DATABASE_USER:-"postgres"}
DB_HOST=${DATABASE_HOST:-"localhost"}
DB_PORT=${DATABASE_PORT:-"5432"}

# 检查参数
if [ -z "$1" ]; then
  echo "❌ 错误: 请指定要恢复的备份文件!"
  echo "用法: ./restore-db.sh <backup_file>"
  echo ""
  echo "可用的备份文件:"
  ls -l "$BACKUP_DIR"/*.backup 2>/dev/null
  exit 1
fi

BACKUP_FILE="$BACKUP_DIR/$1"
if [[ ! "$1" = /* ]] && [[ ! "$1" = ~/* ]]; then
  BACKUP_FILE="$BACKUP_DIR/$1"
fi

# 检查文件是否存在
if [ ! -f "$BACKUP_FILE" ]; then
  echo "❌ 错误: 备份文件不存在: $BACKUP_FILE"
  echo "可用的备份文件:"
  ls -l "$BACKUP_DIR"/*.backup 2>/dev/null
  exit 1
fi

# 确认操作
echo "⚠️  警告: 即将恢复数据库!"
echo "• 数据库: $DB_NAME"
echo "• 备份文件: $BACKUP_FILE"
echo ""
echo "这将覆盖当前数据库中的所有数据!"
read -p "确定要继续吗? (yes/no): " answer

if [ "$answer" != "yes" ]; then
  echo "操作已取消"
  exit 0
fi

# 检查数据库连接
echo "📡 检查数据库连接..."
PGPASSWORD=$DATABASE_PASSWORD psql \
  -h "$DB_HOST" \
  -p "$DB_PORT" \
  -U "$DB_USER" \
  -d "$DB_NAME" \
  -c "\q" > /dev/null 2>&1

if [ $? -ne 0 ]; then
  echo "❌ 无法连接到数据库!"
  echo "请检查数据库配置和连接."
  exit 1
fi

echo "🔄 开始恢复数据..."

# 中断已有连接
echo "• 断开现有连接..."
PGPASSWORD=$DATABASE_PASSWORD psql \
  -h "$DB_HOST" \
  -p "$DB_PORT" \
  -U "$DB_USER" \
  -d "$DB_NAME" \
  -c "
    SELECT pg_terminate_backend(pid)
    FROM pg_stat_activity
    WHERE datname = '$DB_NAME'
    AND pid <> pg_backend_pid();" > /dev/null 2>&1

# 执行恢复
echo "• 恢复数据中..."
PGPASSWORD=$DATABASE_PASSWORD pg_restore \
  -h "$DB_HOST" \
  -p "$DB_PORT" \
  -U "$DB_USER" \
  -d "$DB_NAME" \
  -v \
  --clean \
  --if-exists \
  "$BACKUP_FILE"

if [ $? -eq 0 ]; then
  echo "✅ 数据恢复完成!"
else
  echo "❌ 数据恢复失败!"
  exit 1
fi
